package com.hbfu.zggdwlzzsx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbfu.zggdwlzzsx.entity.Users;
import com.hbfu.zggdwlzzsx.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
@CrossOrigin
public class UsersController {

    @Autowired
    private UsersService usersService;

    @GetMapping("/{id}")
    public Users getUserById(@PathVariable Integer id) {
        return usersService.getById(id);
    }

    @PostMapping
    public boolean saveUser(@RequestBody Users user) {
        return usersService.updateById(user);
    }

    @PutMapping
    public boolean updateUser(@RequestBody Users user) {
        QueryWrapper<Users> qu = new QueryWrapper<>();
        qu.eq("account",user.getAccount());

        return usersService.update(user,qu);
    }

    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable Integer id) {
        return usersService.removeById(id);
    }


    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody Users user) {
        Users validatedUser = usersService.validateUser(user.getAccount(), user.getPassword());
        if (validatedUser != null) {
            return ResponseEntity.ok("登录成功");
        } else {
            return ResponseEntity.badRequest().body("账号或密码错误");
        }
    }


}